package manager;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.DBConnector;

/**
 * Servlet implementation class Login
 */
public class Login extends BaseCMServlet {
	private static final long serialVersionUID = 1L;
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
				
		if (username     == null || 
			password     == null)
		
		{
			    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
				return;
						
		}
		
		DBConnector dbConn = null;
		try {
			dbConn = new DBConnector();
			Statement stmnt = dbConn.getConnection().createStatement();
			ResultSet res = stmnt.executeQuery(String.format("SELECT is_admin, password FROM users WHERE username = '%s'", username));
			
			if (!res.next()) {
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Not registred");
				return;
			}
			
			if (!res.getString("password").equals(password)){
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Wrong password");
				return;
				
			}	
			
			request.getSession().setAttribute("username", username);
			request.getSession().setAttribute("type", res.getBoolean("is_admin") ? "admin" : "non-admin");
			SessionManager.addSession(request.getSession());
			response.sendRedirect("");

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}
